﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using easyList.IO.Reader;
using easyList.IO.Writer;
using easyList.Entities;
using easyList.Tools;
using easyList.Exceptions;

using easyList.Logging;
using easyList.Options;

using easyList.ThirdParty;

namespace easyList
{
    public partial class MainWindow : Form
    {
        
        public MainWindow()
        {
            InitializeComponent();
        }

        //DATAGRID METHODS

        public void loadGlobalArchiveToDataGridView()
        {
            try
            {
                if (Program.globalArchive.contentList == null)
                {
                    return;
                }
                dataGridView1.RowTemplate.Height = 40;
                dataGridView1.DataSource = Program.globalArchive.contentList;
                dataGridView1.AllowUserToResizeColumns = false;
                dataGridView1.ReadOnly = true;
                dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            catch (Exception exc)
            {
               ExceptionTool.showExceptionMessage(exc);
            }
        }

        public void loadFilteredArchiveToDataGridView()
        {
            try
            {
                if (Program.filteredArchive.contentList == null)
                {
                    clearCurrentDataGridView();
                    return;
                }
                dataGridView1.DataSource = Program.filteredArchive.contentList;
                dataGridView1.AllowUserToResizeColumns = false;
                dataGridView1.ReadOnly = true;
                dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }

        }

        //DATAGRID METHODS END

        //STATUSLABEL CONTROL

        void statusLabelShowCurrentItemNumber()
        {
            try
            {   
                if (Program.globalArchive.contentList == null)
                {
                    return;
                }
                toolStripStatusLabel.Text = Program.globalArchive.contentList.Count + " Items in current List";
            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }
        }

        void statusLabelShowFilteredItemNumber(int filteredNumber)
        {
            try
            {
                //if (Program.filteredArchive.contentList == null)
                //{
                //    return;
                //}
                toolStripStatusLabel.Text = filteredNumber + " filtered Items in current List " + "(" + Program.globalArchive.contentList.Count + " Items total)";
            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }
        }
        

        //STATUSLABEL CONTROL END

        public void clearCurrentDataGridView()
        {
            dataGridView1.DataSource = null;
        }

        private void loadUNCPathButton_Click(object sender, EventArgs e)
        {
            try
            {
                //show folder browser dialog
                folderBrowserDialog.ShowDialog();
                string selectedPath = folderBrowserDialog.SelectedPath;

                if (selectedPath == "" || selectedPath == null)
                {
                    return;
                }

                //show source label dialog
                InputSourceWindow inputWindow = new InputSourceWindow();
                inputWindow.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
                inputWindow.ShowDialog();

                //list the files in selected folder
                UNCPathLister lister = UNCPathLister.Instance;
                ArchiveObject newFSF = lister.listFiles(selectedPath);

                //add the files to global archive
                Program.globalArchive.addListToArchive(newFSF.contentList);

                //load data to grid
                if (selectedPath != "" && selectedPath != null)
                {
                    loadGlobalArchiveToDataGridView();
                    statusLabelShowCurrentItemNumber();
                }
            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string svn_revision = "r15";
            MessageBox.Show("Author: Highsense \nEmail: xbl.highsense@googlemail.com \nVersion: 1.0 " + svn_revision, "easyList About", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void readXMLButton_Click(object sender, EventArgs e)
        {

            if (readXMLFileDialog.ShowDialog() == DialogResult.OK)
            {

                string selectedPath = readXMLFileDialog.FileName;

                if (selectedPath != "" && selectedPath != null)
                {
                    XMLReader xmlReader = XMLReader.Instance;
                    ArchiveObject xmlArchive = xmlReader.readXML(selectedPath);
                    if (xmlArchive != null)
                    {
                        Program.globalArchive.addArchiveToArchive(xmlArchive);
                        loadGlobalArchiveToDataGridView();
                        statusLabelShowCurrentItemNumber();
                    }

                }

            }
            else
            {
                return;
            }

        }

        private void saveTXTButton_Click(object sender, EventArgs e)
        {

            saveTXTFileDialog.ShowDialog();
            Program.selectedSavePath = saveTXTFileDialog.FileName;
            if (Program.selectedSavePath != "" && Program.selectedSavePath != null)
            {
                TXTWriter writer = TXTWriter.Instance;
                writer.writeTXT(Program.globalArchive, Program.selectedSavePath);
            }
        }

        private void loadDirButton_Click(object sender, EventArgs e)
        {
            openDirFile.ShowDialog();
            string selectedFilePath = openDirFile.FileName;
            DirPrintReader reader = DirPrintReader.Instance;
            ArchiveObject list = reader.readDirTxt(selectedFilePath);

            Program.globalArchive.addListToArchive(list.contentList);

            loadGlobalArchiveToDataGridView();
            statusLabelShowCurrentItemNumber();

        }

        private void saveXMLButton_Click(object sender, EventArgs e)
        {
            if (Program.globalArchive.contentList == null)
            {
                MessageBox.Show("Nothing to save", "Saving Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            saveXMLFileDialog.Filter = "XML file (*.xml)|*.xml";
            saveXMLFileDialog.DefaultExt = "xml";
            saveXMLFileDialog.AddExtension = true;

            saveXMLFileDialog.ShowDialog();

            Program.selectedSavePath = saveXMLFileDialog.FileName;
            if (Program.selectedSavePath != "" && Program.selectedSavePath != null)
            {
                XMLWriter writer = XMLWriter.Instance;
                writer.writeXML(Program.globalArchive, Program.selectedSavePath);
            }
        }

        private void clearToolStripButton_Click(object sender, EventArgs e)
        {
            clearAll();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            clearAll();
        }

        
        //Clear everything
        private void clearAll()
        {
            try
            {
                Program.globalArchive = new ArchiveObject();
                clearCurrentDataGridView();
                toolStripStatusLabel.Text = "Ready";

            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }
        }

        private void filterToolStripButton_Click(object sender, EventArgs e)
        {
            //filter the list and write result into global filtered list
            string filterString = filterTextInputBox.Text;

            if( filterString == null || filterString == ""){
                //remove filtered archive
                Program.filteredArchive = new ArchiveObject();

                //clear current datagrid
                clearCurrentDataGridView();

                //load global archive
                loadGlobalArchiveToDataGridView();

                //show global number of archive elements
                statusLabelShowCurrentItemNumber();

                return;
            }

            try
            {
                //if global archive list is empty - do nothing
                if (Program.globalArchive.contentList == null){
                    return;
                }

                //if global archive list isnt empty do filtering
                Program.filteredArchive = FilterTool.filterFilename(Program.globalArchive, filterString);

                if (Program.filteredArchive.contentList == null )
                {
                    statusLabelShowFilteredItemNumber(0);
                }
                else {
                    statusLabelShowFilteredItemNumber(Program.filteredArchive.contentList.Count);
                }

                //tool strip label status, todo count filtered
                //toolStripStatusLabel.Text = toolStripStatusLabel.Text + " (" + Program.filteredArchive.contentList.Count + " Items filtered)";

                //load filtered list
                loadFilteredArchiveToDataGridView();

            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }


        }

        private void optionsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            OptionWindow optWindow = new OptionWindow();

            //read configuration from config manager
            OptionManager options = OptionManager.Instance;
            optWindow.allowedFormatsCheckbox.Checked = Boolean.Parse(options.getOptionByName("allowedFormatsEnabled",true).optionValue);
            optWindow.ignoredFormatsCheckbox.Checked = Boolean.Parse(options.getOptionByName("ignoredFormatsEnabled",false).optionValue);

            optWindow.allowedFormatsInput.Text = options.getOptionByName("allowedFormats","mkv").optionValue;
            optWindow.ignoredFormatsInput.Text = options.getOptionByName("ignoredFormats","*").optionValue;

            optWindow.Show();
        }

        private void loadDiskButton_Click(object sender, EventArgs e)
        {
            try
            {
                //show folder browser dialog
                folderBrowserDialog.ShowDialog();
                string selectedPath = folderBrowserDialog.SelectedPath;

                if (selectedPath == "" || selectedPath == null)
                {
                    return;
                }

                //show source label dialog
                InputSourceWindow inputWindow = new InputSourceWindow();
                inputWindow.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
                inputWindow.ShowDialog();

                //list the files in selected folder
                UNCPathLister lister = UNCPathLister.Instance;
                //ArchiveObject newFSF = lister.listFiles(selectedPath);
                ArchiveObject newFSF = lister.listFilesWithSubdirectories(selectedPath);

                //add the files to global archive
                Program.globalArchive.addListToArchive(newFSF.contentList);

                //load data to grid
                if (selectedPath != "" && selectedPath != null)
                {
                    loadGlobalArchiveToDataGridView();
                    statusLabelShowCurrentItemNumber();
                }
            }
            catch (Exception exc)
            {
                ExceptionTool.showExceptionMessage(exc);
            }
        }

        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void readXMLFileDialog_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            Boolean logWindowEnabled = true;
            if (logWindowEnabled)
            {

            LogWindow logWindow = new LogWindow();
            Logger logger = Logger.Instance;
            logger.logWindow = logWindow;

            logger.INFO("EasyList starting...");

          

            int x = this.Location.X;
            int y = this.Location.Y;

            logWindow.Location = new Point(x-300, y);

            this.AddOwnedForm(logWindow);
            logWindow.Show();
            }
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            MediaInfoInvoker.invoke("Z:\\Opasnyj.kvartal.2011.BDRip.1080p.mkv\\Opasnyj.kvartal.2011.D.BDRip.1080p.mkv");
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

    }
}
